import 'package:async/async.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mode/zyj/net/dio_manager.dart';

class FutureBuilderPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FutureBuilderPageState();
  }
}

class _FutureBuilderPageState extends State<FutureBuilderPage> {
  String title = "FutureBuilder";
  final AsyncMemoizer _memoizer = AsyncMemoizer();

  Future _getData() async {
    return _memoizer.runOnce(() async {
      return DioManager.singleton.getNormal(
          "http://api.douban.com/v2/movie/top250",
          data: {'count': 30});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        centerTitle: true,
      ),
      body: FutureBuilder(
        builder: _buildFuture,
        future: _getData(),
      ),
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.title),
          onPressed: () {
            setState(() {
              title = title + ".";
            });
          }),
    );
  }

  Widget _buildFuture(BuildContext context, AsyncSnapshot snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        print('还没有开始网络请求');
        return Text('还没有开始网络请求');
      case ConnectionState.active:
        print('active');
        return Text('ConnectionState.active');
      case ConnectionState.waiting:
        print('waiting');
        return Center(
          child: CircularProgressIndicator(),
        );
      case ConnectionState.done:
        print('done');
        if (snapshot.hasError) return Text('Error: ${snapshot.error}');
        return _createListView(context, snapshot.data);
      default:
        return Text('不明状态');
    }
  }

  Widget _createListView(BuildContext context, Response response) {
    List movies = response.data['subjects'];
    return ListView.builder(
      itemBuilder: (context, index) => _itemBuilder(context, index, movies),
      itemCount: movies.length * 2,
    );
  }

  _itemBuilder(BuildContext context, int index, List movies) {
    if (index.isOdd) {
      return Divider();
    }
    index = index ~/ 2;
    return ListTile(
      title: Text(movies[index]['title']),
      leading: Text(movies[index]['year']),
    );
  }
}
